import { useMemberStore } from '@/store';
import { createRouter, createWebHashHistory } from 'vue-router';

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      component: () => import('@/views/Layout/index.vue'),
      // 首页属于Layout的二级路由
      children: [
        {
          path: '/',
          component: () => import('@/views/Home/index.vue'),
        },
        {
          path: '/category/:id',
          component: () => import('@/views/Category/index.vue'),
        },
        {
          path: '/category/sub/:id',
          component: () => import('@/views/sub/sub.vue'),
        },
        {
          path: '/goods/:id',
          component: () => import('@/views/Goods/index.vue'),
        },
        // 购物车(Layout的二级路由)
        {
          path: '/cart',
          component: () => import('@/views/Cart/index.vue'),
        },
        // 订单页(Layout的二级路由)
        {
          path: '/member/checkout',
          component: () => import('@/views/Checkout/index.vue'),
        },
        {
          path: '/member/pay',
          component: () => import('@/views/Pay/index.vue'),
        },
        // 支付结果页(Layout二级路由)
        {
          path: '/member/pay/callback',
          component: () => import('@/views/Pay/callback.vue'),
        },
        // 会员中心
        {
          path: '/member',
          component: () => import('@/views/Member/Layout/index.vue'),
          children: [
            {
              path: '/member',
              component: () => import('@/views/Member/Home/index.vue'),
            },
            {
              path: '/member/order',
              component: () => import('@/views/Member/Order/index.vue'),
            },
          ],
        },
      ],
    },
    {
      path: '/login',
      component: () => import('@/views/Login/index.vue'),
    },
    {
      path: '/login/callback',
      component: () => import('@/views/Login/callback.vue'),
    },
    {
      path: '/cart',
      component: () => import('@/views/Cart/index.vue'),
    },
  ],
  // 始终滚动到顶部
  scrollBehavior() {
    return {
      top: 0, // 切换路由时,始终返回顶部
      behavior: 'smooth', // 更丝滑的滚动行为
    };
  },
});
router.beforeEach((to) => {
  const member = useMemberStore();
  if (!member.isLogin && to.path.startsWith('/member')) {
    return `/login?target=${to.fullPath}`;
  }
});
export default router;
